package yxy.game.pm2.module.tip.checker;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import yxy.apple.util.PubSub.MethodSubscriber;
import yxy.apple.util.PubSub.SubscriptionMethod;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.unionskillupcost;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.pubsub.CurrencyPublisher;
import yxy.game.pm2.bean.pubsub.CurrencyPublisher.CurrencySubscription;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.player.UnionPlayer;
import yxy.game.pm2.module.union.player.tech.UnionPlayerTech;
import yxy.game.pm2.module.union.player.tech.UnionTech;

public class TipSubscriber_联盟科技 extends MethodSubscriber {

	static private TipSubscriber_联盟科技 instance;

	public static TipSubscriber_联盟科技 getInstance() {
		if (instance == null) {
			instance = new TipSubscriber_联盟科技();
			instance.init();
		}
		return instance;
	}

	private void init() {
		CurrencyPublisher.getInstance().subscribe(this);
	}

	private TipSubscriber_联盟科技() {
	}

	@SubscriptionMethod(Type = CurrencySubscription.class)
	public void receive(CurrencySubscription subscription) {
		String playerCode = subscription.getPlayerCode();
		if (!subscription.checkTypes(allowType())) {
			return;
		}
		new TipHandle().updateTip(playerCode, TipType.联盟_科技按钮, check(playerCode));
	}

	private boolean check(String playerCode) {
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnion(entry);
		if (!result.equals(Result.UnionIn)) {
			return false;// 没有联盟
		}
		UnionPlayer unionPlayer = entry.getUnionPlayer();
		UnionPlayerTech playerTech = unionPlayer.getTech();

		boolean cancost = false;
		for (UnionTech tech : playerTech.getTechList()) {
			if (tech.getLevel() >= tech.data().getLvmax()) {
				return false;// 科技满级
			}
			Collection<Currency> cost = tech.cost();

			cancost = new CurrencyHandle().costCheck(playerCode, cost);
			if (cancost) {
				return cancost;
			}
		}
		return cancost;
	}

	private Set<CurrencyType> allowTypes;

	private Set<CurrencyType> allowType() {
		if (allowTypes != null) {
			return allowTypes;
		}
		allowTypes = new HashSet<>();
		Map<String, unionskillupcost> costdatas = DataCenter.getAllData(unionskillupcost.class);
		for (unionskillupcost data : costdatas.values()) {
			CurrencyType type1 = CurrencyType.forNumber(data.getCosttype1());
			if (type1 != null) {
				allowTypes.add(type1);
			}
			CurrencyType type2 = CurrencyType.forNumber(data.getBegincosttype2());
			if (type2 != null) {
				allowTypes.add(type2);
			}
		}
		return allowTypes;
	}

}
